package com.jqb.hibernatebbs.servlet;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jqb.hibernatebbs.pojo.Bbsmsg;
import com.jqb.hibernatebbs.pojo.Bbsuser;
import com.jqb.hibernatebbs.service.UserService;
import com.jqb.hibernatebbs.service.impl.UserServiceImpl;

public class MessageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String opt = request.getParameter("opt");
		
		UserService userService = new UserServiceImpl();
		
		if(opt!=null&&"see".equals(opt)){
			request.getRequestDispatcher("/WEB-INF/sendMsg.jsp").forward(request, response);
		}
		if(opt!=null&&"send".equals(opt)){
			Bbsmsg msg = new Bbsmsg();
			
			String message = request.getParameter("msg");
			String posttime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
			String re = request.getParameter("receiver");
			
			Bbsuser receiver = (Bbsuser) userService.getUserByName(re); 
			Bbsuser sender = (Bbsuser) request.getSession().getAttribute("user");
			
			
			msg.setMsg(message);
			msg.setPosttime(posttime);
			msg.setSender(sender);
			msg.setReceiver(receiver);
			
			//addInfo是通用接口的所以用UserService和MessageService调用都一样
			userService.addInfo(msg);
			
			response.sendRedirect("/HibernateBBSBeta/carriageServlet");
		}
	}

}
